package com.eva.biz.system;

import com.eva.biz.system.dto.DepartmentImportDTO;
import com.eva.core.annotation.excel.ExcelImportCallback;
import com.eva.core.exception.BusinessException;
import com.eva.dao.system.model.SystemDepartment;
import com.eva.service.system.SystemDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class DepartmentExcelImportCallback implements ExcelImportCallback<DepartmentImportDTO> {

    @Autowired
    private SystemDepartmentService systemDepartmentService;

    @Autowired
    private SystemDepartmentBiz systemDepartmentBiz;

    private ThreadLocal<Map<String, SystemDepartment>> departments = new ThreadLocal<>();

    @Override
    @Transactional
    public int callback(List<DepartmentImportDTO> data) {
        if (CollectionUtils.isEmpty(data)) {
            return 0;
        }
        int total = 0;
        departments.set(new HashMap<>());
        for (DepartmentImportDTO dto : data) {
            SystemDepartment department = new SystemDepartment();
            BeanUtils.copyProperties(dto, department);
            department.setPhone(dto.getPhone() == null ? "" : "" + dto.getPhone());
            // 父部门处理
            SystemDepartment parentDepartment = this.getDepartment(dto.getParentCode());
            if (parentDepartment != null) {
                department.setParentId(parentDepartment.getId());
            }
            try {
                systemDepartmentBiz.create(department);
                total++;
            } catch (BusinessException e) {
                log.info(e.getMessage());
            }
        }
        return total;
    }

    /**
     * 根据编码获取
     * @param code
     * @return
     */
    private SystemDepartment getDepartment (String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        SystemDepartment department = departments.get().get(code);
        if (department != null) {
            return department;
        }
        SystemDepartment queryParentDto = new SystemDepartment();
        queryParentDto.setCode(code);
        queryParentDto.setDeleted(Boolean.FALSE);
        department = systemDepartmentService.findOne(queryParentDto);
        if (department != null) {
            departments.get().put(code, department);
            return department;
        }
        return null;
    }
}
